<template>
  <div class="app-container">
    <!-- 过滤 -->
    <div class="filter-container">
      <el-input v-model="listQuery.returnOrderNumber" placeholder="退货单号" style="width: 200px;" class="filter-item" />
      <el-input v-model="listQuery.shippingOrderNumber" placeholder="发货单号" style="width: 200px;" class="filter-item" />
      <el-input v-model="listQuery.customerName" placeholder="客户名称" style="width: 200px;" class="filter-item" />
      <el-date-picker
        v-model="listQuery.returnDate"
        type="daterange"
        range-separator="至"
        value-format="yyyy-MM-dd HH:mm:ss"
        start-placeholder="退货日期"
        end-placeholder="退货日期"
        @change="changeDate"
      />
      <el-select v-model="listQuery.warehousingStatus" default-first-option placeholder="入库状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in warehousingStatus" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>

      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-refresh" @click="resetHandler">
        重置
      </el-button>
    </div>
    <div style="margin-bottom: 10px;">
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="openDialog">
        添加
      </el-button>
      <el-popconfirm
        :title="`是否确认删除销售合同编号为 ${ids} 的数据项`"
        @onConfirm="removeData(ids)"
      >
        <el-button slot="reference" :disabled="!ids.length" class="filter-item" type="danger" icon="el-icon-delete">
          删除
        </el-button>
      </el-popconfirm>
    </div>

    <!-- 表格 -->
    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;" @selection-change="handleSelectionChange">
      <el-table-column type="selection" />
      <el-table-column align="center" label="编号">
        <template slot-scope="scope">
          {{ (listQuery.page - 1) * listQuery.size + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="退货订单号" prop="returnOrderNumber" />
      <el-table-column align="center" label="发货单号" prop="shippingOrderNumber" />
      <el-table-column align="center" label="合同编号" prop="deliveryOrder.deliveryNumber" />
      <el-table-column align="center" label="客户名称" prop="deliveryOrder.customerName" />
      <el-table-column align="center" label="退货日期" prop="returnDate" />
      <el-table-column align="center" label="退款金额" prop="refundAmount" />
      <el-table-column align="center" label="入库状态" prop="warehousingStatus">
        <template slot-scope="{row}">
          <el-tag v-show="row.warehousingStatus == 0" type="success">未入库</el-tag>
          <el-tag v-show="row.warehousingStatus == 1" type="danger">已入库</el-tag>
          <el-tag v-show="row.warehousingStatus == 2" type="danger">入库中</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" width="130" label="操作">
        <template slot-scope="{row}">
          <el-button type="primary" icon="el-icon-edit" circle @click="openDialog(row)" />
          <el-button type="danger" icon="el-icon-delete" circle @click="removeHandler(row.id)" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="getList" />

    <!-- 对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form">
        <el-form-item label="发货单号" :label-width="formLabelWidth">
          <el-input
            v-model="form.shippingOrderNumber"
            :disabled="true"
          />
          <el-button type="primary" size="small" title="选择发货单" @click="openDeliveryOrderDialog">选择</el-button>
        </el-form-item>
        <el-form-item label="退货日期" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.returnDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="退货原因" :label-width="formLabelWidth">
          <el-input v-model="form.reasonReturn" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.remark" type="textarea" :rows="3" />
        </el-form-item>
        <el-divider>
          <span>
            退货明细信息
            <el-tooltip effect="dark" content="1111" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
          </span>
        </el-divider>

        <el-form-item v-if="form.salesReturnDetail.id" label="序号" :label-width="formLabelWidth">
          <el-input v-model="form.salesReturnDetail.id" disabled />
        </el-form-item>
        <el-form-item label="物料" :label-width="formLabelWidth">
          <el-input v-model="form.salesReturnDetail.material" />
        </el-form-item>
        <el-form-item label="型号" :label-width="formLabelWidth">
          <el-input v-model="form.salesReturnDetail.model" />
        </el-form-item>
        <el-form-item label="规格" :label-width="formLabelWidth">
          <el-input v-model="form.salesReturnDetail.specification" />
        </el-form-item>
        <el-form-item label="单位" :label-width="formLabelWidth">
          <el-input v-model="form.salesReturnDetail.unit" />
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth">
          <el-input v-model="form.salesReturnDetail.price" />
        </el-form-item>
        <el-form-item label="订货数量" :label-width="formLabelWidth">
          <el-input v-model="form.salesReturnDetail.orderQuantity" />
        </el-form-item>
        <el-form-item label="发货数量" :label-width="formLabelWidth">
          <el-input v-model="form.salesReturnDetail.shippedQuantity" />
        </el-form-item>
        <el-form-item label="退货数量" :label-width="formLabelWidth">
          <el-input v-model="form.salesReturnDetail.returnQuantity" />
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.salesReturnDetail.remarks" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 选择发货单对话框 -->
    <el-dialog title="选择发货单" :visible.sync="deliveryOrderDialogVisible">
      <div>
        <el-input v-model="deliveryOrderData.listQuery.deliveryNumber" placeholder="发货编号" style="width: 140px;margin-right: 5px;" />
        <el-input v-model="deliveryOrderData.listQuery.contractNumber" placeholder="合同编号" style="width: 140px;margin-right: 5px;" />
        <el-input v-model="deliveryOrderData.listQuery.customerName" placeholder="客户名称" style="width: 140px;margin-right: 5px;" />
        <el-date-picker
          v-model="listQuery.deliveryDate"
          type="daterange"
          range-separator="至"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="交货日期"
          end-placeholder="交货日期"
          @change="changeDeliveryDate"
        />
        <el-button type="primary" icon="el-icon-search" @click="handleDeliveryOrderFilter">
          {{ $t('table.search') }}
        </el-button>
        <el-button class="filter-item" type="primary" icon="el-icon-refresh" @click="resetDeliveryOrderHandler">
          重置
        </el-button>
      </div>
      <el-table :data="deliveryOrderData.list">
        <el-table-column align="center" label="编号">
          <template slot-scope="scope">
            {{ (deliveryOrderData.listQuery.page - 1) * deliveryOrderData.listQuery.size + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="发货编号" prop="deliveryNumber" />
        <el-table-column align="center" label="合同编号" prop="contractNumber" />
        <el-table-column align="center" label="客户名称" prop="customerName" />
        <el-table-column align="center" label="送货方式" prop="deliveryMethod" />
        <el-table-column align="center" label="交货日期" prop="deliveryDate" />
        <el-table-column align="center" label="收货地址" prop="shippingAddress" />
        <el-table-column align="center" label="联系人" prop="contactPerson" />
        <el-table-column align="center" label="联系电话" prop="contactPhone" />
        <el-table-column align="center" label="出库状态" prop="outboundStatus">
          <template slot-scope="{row}">
            <el-tag v-show="row.outboundStatus == 0" type="success">未出库</el-tag>
            <el-tag v-show="row.outboundStatus == 1" type="danger">已出库</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right">
          <template slot-scope="{row}">
            <el-button type="primary" :disabled="form.shippingOrderNumber === row.id" @click="chooseDeliveryOrder(row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="deliveryOrderData.total > 0" :total="deliveryOrderData.total" :page.sync="deliveryOrderData.listQuery.page" :limit.sync="deliveryOrderData.listQuery.size" @pagination="getDeliveryOrderList" />
    </el-dialog>
  </div>
</template>
<script>
import { fetchList, remove, save, edit } from '@/api/market-return'
import { fetchList as deliveryOrderFetchList } from '@/api/delivery-order'
import Pagination from '@/components/Pagination'
const defaultListQuery = {
  page: 1,
  size: 10,
  returnOrderNumber: '',
  shippingOrderNumber: '',
  customerName: '',
  returnDate: ''
}
export default {
  name: 'MarketReturn',
  components: { Pagination },
  data() {
    return {
      // 功能标题
      title: '销售退货',
      tableKey: 0,
      listLoading: false,
      // 查询参数
      listQuery: defaultListQuery,
      // 表格数据
      list: [],
      // 总数
      total: 0,
      // 对话框显示
      dialogFormVisible: false,
      // 对话框宽度
      formLabelWidth: '120px',
      // 表单
      form: {
        salesReturnDetail: {}
      },
      // 对话框标题
      dialogTitle: '',
      // 复选框选中的id数组
      ids: [],
      returnDate: '',
      warehousingStatus: [
        {
          key: '0',
          label: '未入库'
        },
        {
          key: '1',
          label: '已入库'
        },
        {
          key: '2',
          label: '已入库'
        }
      ],
      deliveryOrderData: {
        // 查询参数
        listQuery: {
          page: 1,
          size: 10,
          deliveryNumber: '',
          contractNumber: '',
          customerName: '',
          deliveryDate: ''
        },
        // 总数
        total: 0,
        list: []
      },
      deliveryOrderDialogVisible: false,
      deliveryDate: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 选择发货单
    chooseDeliveryOrder(row) {
      this.form.shippingOrderNumber = row.id
      // 关闭对话框
      this.deliveryOrderDialogVisible = false
      this.$message({
        message: '发货单选择成功',
        type: 'success'
      })
    },
    // 打开发货单对话框
    openDeliveryOrderDialog() {
      this.deliveryOrderDialogVisible = !this.deliveryOrderDialogVisible
      this.getDeliveryOrderList()
    },
    // 获取发货单列表
    getDeliveryOrderList() {
      deliveryOrderFetchList(this.deliveryOrderData.listQuery).then(res => {
        this.deliveryOrderData.list = res.data.data
        this.deliveryOrderData.total = res.data.total
      })
    },
    handleDeliveryOrderFilter() {
      this.deliveryOrderData.listQuery.deliveryDate = this.deliveryDate
      this.getDeliveryOrderList()
    },
    changeDeliveryDate(value) {
      this.deliveryDate = value.join('|')
    },
    resetDeliveryOrderHandler() {
      this.deliveryDate = ''
      this.deliveryOrderData.listQuery = {
        page: 1,
        size: 10,
        deliveryNumber: '',
        contractNumber: '',
        customerName: '',
        deliveryDate: ''
      }
    },
    /**
     * 退货日期关闭触发
     * @param { Array } value 数组
     */
    changeDate(value) {
      this.returnDate = value.join('|')
    },
    /**
     * 查询
     */
    handleFilter() {
      this.listQuery.returnDate = this.returnDate
      this.getList()
    },
    /**
     * 重置
     */
    resetHandler() {
      this.listQuery = {
        page: 1,
        size: 10,
        returnOrderNumber: '',
        shippingOrderNumber: '',
        customerName: '',
        returnDate: ''
      }
      this.returnDate = ''
    },
    getList() {
      fetchList(this.listQuery).then(res => {
        const { data } = res
        console.log(data.data)
        this.total = data.total
        this.list = data.data
        // 切割字符串转成数组
        this.listQuery.returnDate = this.listQuery.returnDate instanceof Array ? this.listQuery.returnDate.split('|') : ''
      }).finally(() => {
        this.listLoading = false
      })
    },
    /**
     * 选中改变触发
     * @param { Array } val 选中的行数据
     */
    handleSelectionChange(val) {
      this.ids = val.map(item => item.id)
    },
    /**
     * 开启对话框
     * @param {*} row 行数据
     */
    openDialog(row) {
      this.dialogFormVisible = true
      this.form = {
        salesReturnDetail: {}
      }
      this.detailForm = {}
      if (row.id) {
        this.dialogTitle = `修改${this.title}`
        this.form = { ...row }
      } else { // 新增
        this.dialogTitle = `添加${this.title}`
      }
    },
    // 单个删除
    removeHandler(id) {
      // console.log(ids)
      this.$confirm(`是否确认删除销售合同编号为 ${id} 的数据项`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(id)
        this.removeData([id])
      }).catch(() => {})
    },
    // 执行删除
    removeData(ids) {
      remove(ids).then(res => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      }).finally(() => {
        this.getList()
      })
    },
    // 提交表单
    submitForm() {
      if (this.form.id) {
        console.log('修改')
        this.modifyData()
      } else {
        console.log('新增')
        this.saveData()
      }
    },
    saveData() {
      this.form.deliveryOrderId = this.form.shippingOrderNumber
      this.form.warehousingStatus = 0
      save(this.form).then(res => {
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success',
          duration: 5000
        })
      }).finally(() => {
        this.getList()
      })
    },
    modifyData() {
      edit(this.form).then(res => {
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success',
          duration: 5000
        })
      }).finally(() => {
        this.getList()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
